{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Ansible 任务管理</title>
    <link href="{% static 'layui.css' %}" rel="stylesheet">
    <script src="{% static 'layui.js' %}"></script>
    <script src="{% static 'jquery-3.6.0.min.js' %}"></script>
    <style>
        .task-container {
            max-width: 900px;
            margin: 30px auto;
            background: #fff;
            border-radius: 6px;
            box-shadow: 0 2px 15px rgba(0, 0, 0, 0.08);
            padding: 25px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        /* 步骤进度条样式 */
        .step-progress {
            display: flex;
            justify-content: center;
            margin: 0 auto 30px;
            max-width: 500px;
            position: relative;
        }

        .step-progress:before {
            content: '';
            position: absolute;
            top: 15px;
            left: 50px;
            right: 50px;
            height: 2px;
            background: #e8e8e8;
            z-index: 1;
        }

        .step-item {
            text-align: center;
            z-index: 2;
            position: relative;
            flex: 1;
        }

        .step-number {
            display: inline-block;
            width: 30px;
            height: 30px;
            line-height: 30px;
            border-radius: 50%;
            background: #e8e8e8;
            color: #999;
            font-weight: bold;
            font-size: 14px;
            margin-bottom: 8px;
            transition: all 0.3s ease;
        }

        .step-item.active .step-number {
            background: #1E9FFF;
            color: white;
            transform: scale(1.1);
        }

        .step-title {
            font-size: 14px;
            color: #777;
            white-space: nowrap;
        }

        .step-item.active .step-title {
            color: #1E9FFF;
            font-weight: 600;
        }

        /* 第一步内容区域 */
        .step-content {
            display: none;
            animation: fadeIn 0.5s ease;
        }

        .step-content.active {
            display: block;
        }

        .section-header {
            text-align: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
        }

        .section-header h2 {
            margin: 0;
            color: #333;
            font-size: 22px;
            font-weight: 600;
        }

        .section-header p {
            margin: 8px 0 0;
            color: #777;
            font-size: 15px;
        }

        /* 表格美化 */
        .host-table-container {
            margin-bottom: 25px;
            border-radius: 6px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .host-table-container .layui-table th {
            background-color: #f8fafc;
            font-weight: 600;
            color: #444;
        }

        .host-table-container .layui-table tbody tr {
            transition: all 0.2s ease;
        }

        .host-table-container .layui-table tbody tr:hover {
            background-color: rgba(30, 159, 255, 0.03);
        }

        /* 已选主机区 */
        .selected-hosts-card {
            background: #f9fbfd;
            border-radius: 6px;
            padding: 20px;
            margin: 20px 0 25px;
            border: 1px solid #eef2f7;
            box-shadow: inset 0 0 15px rgba(0, 0, 0, 0.02);
        }

        .selected-hosts-card h3 {
            margin: 0 0 15px;
            font-size: 16px;
            color: #555;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .selected-hosts-card h3 i {
            margin-right: 8px;
            color: #1E9FFF;
        }

        .selected-hosts-card .hosts-display {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
        }

        .host-tag {
            background: #e8f4ff;
            border: 1px solid #c1e0ff;
            color: #1E9FFF;
            padding: 8px 15px;
            border-radius: 30px;
            font-size: 14px;
            display: flex;
            align-items: center;
            transition: all 0.2s ease;
        }

        .host-tag i {
            margin-left: 8px;
            cursor: pointer;
        }

        .host-tag i:hover {
            color: #ff5722;
        }

        /* 按钮区域 */
        .button-container {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
            margin-top: 15px;
        }

        .layui-btn {
            border-radius: 4px;
            font-weight: 500;
            padding: 0 22px;
            height: 38px;
            line-height: 38px;
            transition: all 0.2s ease;
        }

        .layui-btn-primary {
            border: 1px solid #dcdfe6;
        }

        .layui-btn-primary:hover {
            border-color: #c0c4cc;
            color: #666;
        }

        .layui-btn-normal {
            background-color: #1E9FFF;
        }

        .layui-btn-normal:hover {
            background-color: #0d8df2;
            box-shadow: 0 2px 8px rgba(30, 159, 255, 0.3);
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .step-progress:before {
                left: 40px;
                right: 40px;
            }

            .host-tag {
                padding: 6px 12px;
                font-size: 13px;
            }
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .confirmation-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            padding: 30px;
            max-width: 700px;
            margin: 0 auto;
        }

        .confirmation-header {
            text-align: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
        }

        .confirmation-header h2 {
            margin: 0 0 5px;
            color: #333;
            font-size: 22px;
            font-weight: 600;
        }

        .confirmation-header p {
            margin: 0;
            color: #666;
            font-size: 15px;
        }

        .confirmation-body {
            padding: 15px;
            background: #f9fbfd;
            border-radius: 6px;
            border: 1px solid #eef2f7;
        }

        .info-item {
            display: flex;
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
        }

        .info-item:last-child {
            border-bottom: none;
        }

        .info-label {
            min-width: 130px;
            font-weight: 500;
            color: #555;
        }

        .info-value {
            flex: 1;
            color: #333;
        }

        .confirmation-footer {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 30px;
        }

        .confirmation-footer .layui-btn {
            border-radius: 4px;
            font-weight: 500;
            padding: 0 30px;
            height: 38px;
            line-height: 38px;
            transition: all 0.2s ease;
            min-width: 120px;
        }

        .confirmation-footer .btn-prev {
            background-color: #fff;
            color: #1E9FFF;
            border: 1px solid #1E9FFF;
        }

        .confirmation-footer .btn-submit {
            background-color: #1E9FFF;
            color: white;
        }

        .confirmation-footer .btn-prev:hover {
            background-color: #e6f2ff;
        }

        .confirmation-footer .btn-submit:hover {
            background-color: #0d8df2;
            box-shadow: 0 4px 12px rgba(30, 159, 255, 0.3);
        }
    </style>
</head>
<body>
<div class="task-container">
    <!-- 步骤进度条 -->
    <div class="step-progress">
        <div class="step-item active" id="step1-progress">
            <div class="step-number">1</div>
            <div class="step-title">选择主机</div>
        </div>
        <div class="step-item" id="step2-progress">
            <div class="step-number">2</div>
            <div class="step-title">配置任务</div>
        </div>
        <div class="step-item" id="step3-progress">
            <div class="step-number">3</div>
            <div class="step-title">确认信息</div>
        </div>
    </div>

    <!-- 第一步 - 选择主机（美化后） -->
    <div id="step1" class="step-content active">
        {#        <div class="section-header">#}
        {#            <h2>创建新任务</h2>#}
        {#            <p>通过引导式流程创建新的Ansible任务</p>#}
        {#        </div>#}

        <!-- 主机表格容器 -->
        <div class="host-table-container">
            <input type="hidden" name="host" id="hostInput">
            <table id="hostTable" lay-filter="hostTable"></table>
        </div>

        <!-- 已选主机显示区 -->
        <div class="selected-hosts-card" id="selected-hosts-container" style="display: none;">
            <h3></i> 已选主机 (<span id="selected-count">0</span> 台)</h3>
            <div class="hosts-display" id="selected-hosts-display"></div>
        </div>

        <!-- 按钮区域 -->
        <div class="button-container">
            <button type="button" class="layui-btn layui-btn-primary" onclick="cancelTask()">取消</button>
            <button type="button" class="layui-btn layui-btn-normal" onclick="nextStep()">下一步</button>
        </div>
    </div>

    <!-- 步骤2 - 配置任务（美化后） -->
    <div id="step2" class="layui-panel step-content" style="display: none; border: none; box-shadow: none;">


        {#    <div style="background-color: #f8f9fa; border-radius: 8px; padding: 15px; margin-bottom: 25px;">#}
        {#        <div style="display: flex; align-items: center; margin-bottom: 10px;">#}
        {#            <i class="layui-icon layui-icon-user" style="font-size: 18px; color: #1E9FFF; margin-right: 10px;"></i>#}
        {#            <span style="font-weight: 600; font-size: 15px;">已选主机</span>#}
        {#            <span id="selected-host-info" style="margin-left: auto; font-size: 14px; color: #666;">(1台)</span>#}
        {#        </div>#}
        {#        <div class="host-card" style="background: white; border-radius: 6px; padding: 15px; border: 1px solid #eaeaea; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">#}
        {#            <!-- 主机卡片会由JavaScript动态填充 -->#}
        {#        </div>#}
        {#    </div>#}

        <form class="layui-form"
              style="padding: 15px; background: white; border-radius: 8px; border: 1px solid #eaeaea; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
            <!-- 任务参数区域 -->
            <div class="section-title"
                 style="display: flex; align-items: center; margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #f0f0f0;">
                <i class="layui-icon layui-icon-set" style="font-size: 18px; color: #1E9FFF; margin-right: 10px;"></i>
                <span style="font-weight: 600; font-size: 16px;">任务参数</span>
            </div>

            <div class="layui-form-item" style="margin-bottom: 25px;">
                <label class="layui-form-label" style="font-weight: 500;">任务名称</label>
                <div class="layui-input-block">
                    <input type="text" name="taskName" autocomplete="off" placeholder="请输入任务名称"
                           lay-verify="required" class="layui-input" style="border-radius: 4px; height: 40px;">
                </div>
            </div>

            <div class="layui-row" style="margin-bottom: 20px;">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label" style="font-weight: 500;">详细等级</label>
                        <div class="layui-input-block">
                            <input type="text" name="detail_level" autocomplete="off" placeholder="默认为0"
                                   class="layui-input" style="border-radius: 4px; height: 40px;">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label" style="font-weight: 500;">并发数</label>
                        <div class="layui-input-block">
                            <input type="number" name="forks" placeholder="默认为5" lay-verify="required"
                                   autocomplete="off" class="layui-input" style="border-radius: 4px; height: 40px;">
                        </div>
                    </div>
                </div>
            </div>

            <div class="layui-form-item" style="margin-bottom: 25px;">
                <label class="layui-form-label" style="font-weight: 500;">任务类型</label>
                <div class="layui-input-block">
                    <select name="taskType" lay-filter="aihao" class="layui-select" style="border-radius: 4px;">
                        <option value="">请选择任务类型</option>
                        <option value="playbook">playbook</option>
                        <option value="ad-hoc">ad-hoc</option>
                        <option value="script">script</option>

                    </select>
                </div>
            </div>

            <!-- Playbook区域 -->
            <div id="playbookArea"
                 style="display: none; background: #f8f9fa; border-radius: 6px; padding: 20px; margin-bottom: 25px;">
                <div class="layui-form-item">
                    <label class="layui-form-label" style="font-weight: 400;">脚本选择</label>
                    <div class="layui-input-block">
                        <select name="playbook" lay-search="" lay-creatable="" class="layui-select"
                                style="border-radius: 4px;">
                            <option value="">请选择 Playbook</option>
                            {% for pb in playbooks %}
                                {% if pb.script_type == 'playbook' %}
                                    <option value="{{ pb.id }}">{{ pb.name }}</option>
                                {% endif %}
                            {% endfor %}
                        </select>
                    </div>
                </div>
            </div>
            {#   script 区域#}
            <div id="scriptArea"
                 style="display: none; background: #f8f9fa; border-radius: 6px; padding: 20px; margin-bottom: 25px;">
                <div class="layui-form-item">
                    <label class="layui-form-label" style="font-weight: 400;">脚本选择</label>
                    <div class="layui-input-block">
                        <select name="script" lay-search="" lay-creatable="" class="layui-select"
                                style="border-radius: 4px;">
                            <option value="">请选择shell脚本</option>
                            {% for pb in playbooks %}
                                {% if pb.script_type == 'shell' %}
                                    <option value="{{ pb.id }}">{{ pb.name }}</option>
                                {% endif %}
                            {% endfor %}
                        </select>
                    </div>
                </div>
            </div>
            <!-- Ad-hoc区域 -->
            <div id="adhocArea"
                 style="display: none; background: #f8f9fa; border-radius: 6px; padding: 20px; margin-bottom: 25px;">
                <div class="layui-form-item">
                    <label class="layui-form-label" style="font-weight: 500;">模块名</label>
                    <div class="layui-input-block">
                        <input type="text" name="module" placeholder="例如：ping, shell, copy 等"
                               class="layui-input" style="border-radius: 4px; height: 40px;">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label" style="font-weight: 500;">参数</label>
                    <div class="layui-input-block">
                        <input type="text" name="arguments" placeholder="例如：chdir=/tmp echo 'hello'"
                               class="layui-input" style="border-radius: 4px; height: 40px;">
                    </div>
                </div>
            </div>

            <!-- 按钮区域 -->
            <div class="layui-form-item" style="margin-top: 30px; text-align: right;">
                <button type="button" class="layui-btn layui-btn-primary"
                        style="border-radius: 4px; height: 38px; line-height: 38px; width: 100px;" onclick="prevStep()">
                    上一步
                </button>
                <button type="button" class="layui-btn"
                        style="border-radius: 4px; height: 38px; line-height: 38px; width: 100px; margin-left: 15px; background-color: #1E9FFF;"
                        onclick="nextStep()">下一步
                </button>
            </div>
        </form>
    </div>
    <div id="step3" class="step-content" style="display: none;">
        <form class="layui-form">
            <div class="confirmation-container">

                <div class="confirmation-body">
                    <div class="info-item">
                        <div class="info-label">主机：</div>
                        <div class="info-value" id="confirmHost"></div>
                    </div>

                    <div class="info-item">
                        <div class="info-label">任务名称：</div>
                        <div class="info-value" id="confirmTaskName"></div>
                    </div>

                    <div class="info-item">
                        <div class="info-label">任务类型：</div>
                        <div class="info-value" id="confirmTaskType"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">forks：</div>
                        <div class="info-value" id="confirmForks"></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">详情等级：</div>
                        <div class="info-value" id="confirmDetail"></div>
                    </div>
                    <div class="info-item" id="confirmPlaybook" style="display: none;">
                        <div class="info-label">Playbook脚本：</div>
                        <div class="info-value"><span></span></div>
                    </div>
                    <div class="info-item" id="confirmScript" style="display: none;">
                        <div class="info-label">shell脚本：</div>
                        <div class="info-value"><span></span></div>
                    </div>
                    <div class="info-item" id="confirmAdHocModule" style="display: none;">
                        <div class="info-label">模块名：</div>
                        <div class="info-value"><span></span></div>
                    </div>

                    <div class="info-item" id="confirmAdHocArgs" style="display: none;">
                        <div class="info-label">参数：</div>
                        <div class="info-value"><span></span></div>
                    </div>
                </div>

                <div class="confirmation-footer">
                    <button type="button" class="layui-btn btn-prev" onclick="prevStep()">上一步</button>
                    <button type="button" class="layui-btn btn-submit" onclick="submitFinalData()">提交任务</button>
                </div>
            </div>
        </form>
    </div>

</div>


<script>
    let currentStep = 1;

    function updateStepProgress(step) {
        document.querySelectorAll('.step-item').forEach(item => {
            item.classList.remove('active');
        });

        const stepElement = document.getElementById(`step${step}-progress`);
        if (stepElement) {
            stepElement.classList.add('active');
        }
    }

    function updateSelectedHostDisplay(checkStatus) {
        const selectedHosts = checkStatus.data;
        const container = $('#selected-hosts-container');
        const display = $('#selected-hosts-display');
        const count = $('#selected-count');

        if (selectedHosts.length === 0) {
            container.hide();
            return;
        }

        count.text(selectedHosts.length);

        display.empty();
        selectedHosts.forEach(host => {
            display.append(`
                <div class="host-tag">
                    ${host.hostname || host.ip || '未知主机'}
{#                    <i class="layui-icon layui-icon-close remove-host" data-id="${host.id}"></i>#}
                </div>
            `);
        });

        container.show();


    }

    // 辅助函数 - 更新选中状态
    function updateHostSelection() {
        const checkStatus = layui.table.checkStatus('hostTable');
        updateSelectedHostDisplay(checkStatus);  // 选择主机后下面展示
        updateHostInput(checkStatus);
    }

    // 辅助函数 - 更新主机输入值
    function updateHostInput(checkStatus) {
        const selectedHosts = checkStatus.data;
        const hostListStr = selectedHosts.map(item => item.ip).join(',');
        const selectedHostIds = selectedHosts.map(item => item.id);

        $('#hostInput').val(hostListStr);
        $('#hostInput').data('hostIds', selectedHostIds);
    }

    function showStep(step) {
        document.querySelectorAll('.step-content').forEach(el => el.style.display = 'none');
        document.getElementById('step' + step).style.display = 'block';
        updateStepProgress(step);
    }

    window.nextStep = function () {
        if (currentStep < 4) {
            if (currentStep === 1) {
                const hostInput = document.getElementById('hostInput');
                const hostValue = hostInput ? hostInput.value.trim() : '';

                if (!hostValue) {

                    layer.msg('请先选择主机', {icon: 0});
                    return;
                }

                document.getElementById('confirmHost').innerText = hostValue;

            } else if (currentStep === 2) {
                // 获取任务名称
                const taskNameInput = document.querySelector("input[name='taskName']");
                const taskName = taskNameInput ? taskNameInput.value.trim() : '';

                if (!taskName) {

                    layer.msg('任务名称不能为空', {icon: 0});

                    return;
                }

                // 获取任务类型
                const taskTypeSelect = document.querySelector("select[name='taskType']");
                let taskTypeValue = '';
                let taskTypeText = '未选择';

                if (taskTypeSelect) {
                    taskTypeValue = taskTypeSelect.value;
                    const selectedOption = taskTypeSelect.options[taskTypeSelect.selectedIndex];
                    taskTypeText = selectedOption ? selectedOption.text : '未选择';
                }

                if (!taskTypeValue) {

                    layer.msg('请选择任务类型', {icon: 0});

                    return;
                }

                const detailLevelInput = document.querySelector("input[name='detail_level']");
                const forksInput = document.querySelector("input[name='forks']");
                const detailLevel = detailLevelInput.value.trim() === "" ? 0 : detailLevelInput.value.trim();
                const forks = forksInput.value.trim() === "" ? 5 : forksInput.value.trim();

                console.log(detailLevel, forks);
                console.log(detailLevel, forks)

                // 设置确认页内容
                document.getElementById('confirmTaskName').innerText = taskName;
                document.getElementById('confirmTaskType').innerText = taskTypeText;
                document.getElementById('confirmForks').innerText = forks;
                document.getElementById('confirmDetail').innerText = detailLevel;


                // 根据任务类型判断 Playbook 或 Ad-Hoc 的输入
                if (taskTypeValue === 'playbook') {
                    const playbookSelect = document.querySelector("select[name='playbook']");

                    if (!playbookSelect || !playbookSelect.value) {

                        layer.msg('请选择 Playbook', {icon: 0});

                        return;
                    }

                    const playbookText = playbookSelect.options[playbookSelect.selectedIndex].text;
                    document.querySelector("#confirmPlaybook span").innerText = playbookText;
                    document.getElementById('confirmPlaybook').style.display = 'flex';
                    document.getElementById('confirmAdHocModule').style.display = 'none';
                    document.getElementById('confirmAdHocArgs').style.display = 'none';
                    document.getElementById('confirmScript').style.display = 'none';


                } else if (taskTypeValue === 'script') {
                    const scriptSelect = document.querySelector("select[name='script']");

                    if (!scriptSelect || !scriptSelect.value) {

                        layer.msg('请选择shell脚本', {icon: 0});

                        return;
                    }

                    const scriptText = scriptSelect.options[scriptSelect.selectedIndex].text;
                    document.querySelector("#confirmScript span").innerText = scriptText;
                    document.getElementById('confirmScript').style.display = 'flex';
                    document.getElementById('confirmAdHocModule').style.display = 'none';
                    document.getElementById('confirmAdHocArgs').style.display = 'none';
                    document.getElementById('confirmPlaybook').style.display = 'none';


                } else if (taskTypeValue === 'ad-hoc') {
                    const moduleInput = document.querySelector("input[name='module']");
                    const argsInput = document.querySelector("input[name='arguments']");

                    const module = moduleInput ? moduleInput.value.trim() : '';
                    const argumentsVal = argsInput ? argsInput.value.trim() : '';

                    if (!module) {

                        layer.msg('模块名不能为空', {icon: 0});

                        return;
                    }

                    document.querySelector("#confirmAdHocModule span").innerText = module;
                    document.querySelector("#confirmAdHocArgs span").innerText = argumentsVal;
                    document.getElementById('confirmAdHocModule').style.display = 'flex';
                    document.getElementById('confirmAdHocArgs').style.display = 'flex';
                    document.getElementById('confirmPlaybook').style.display = 'none';
                    document.getElementById('confirmScript').style.display = 'none';

                }
            }

            // 所有验证通过后才允许下一步
            currentStep++;
            showStep(currentStep);
        }
    };

    window.prevStep = function () {
        if (currentStep > 1) {
            currentStep--;
            showStep(currentStep);
        }
    };

    // 取消按钮
    function cancelTask() {
        // 获取当前窗口的layer索引
        var index = parent.layer.getFrameIndex(window.name);
        // 关闭当前弹出层
        parent.layer.close(index);
    }

    layui.use('table', function () {
        var table = layui.table;
        var form = layui.form;

        // 监听任务类型下拉框变化
        form.on('select(aihao)', function (obj) {
            const selected = obj.value; // 获取选中的值

            if (selected === 'playbook') { // playbook
                $('#playbookArea').show();
                $('#adhocArea').hide();
                $('#scriptArea').hide();

            } else if (selected === 'ad-hoc') { // ad-hoc
                $('#adhocArea').show();

                $('#playbookArea').hide();
                $('#scriptArea').hide();

            } else if (selected === 'script') { // script
                $('#scriptArea').show();
                $('#playbookArea').hide();
                $('#adhocArea').hide();

            } else {
                $('#playbookArea').hide();
                $('#adhocArea').hide();
                $('#scriptArea').hide();

            }
        });
        // 已知数据渲染
        table.render({
            elem: '#hostTable',
            url: '{% url 'host_manager:get_host_list_api' %}',
            page: true, // 是否显示分页
            limits: [5, 10, 50, 100, 200, 500, 9999],
            limit: 5,// 每页默认显示的数量
            cols: [[ //标题栏
                {type: 'checkbox', fixed: 'left'},
                {
                    field: 'hostname',
                    title: '主机名'
                },
                {
                    field: 'ip',
                    title: 'IP地址',
                    sort: true
                },
                {
                    field: 'port',
                    title: '端口'
                },
                {
                    field: 'username',
                    title: '用户名'
                },
            ]],
            done: function (res, curr, count) {
                updateHostSelection();
            }

        });
        // 触发表格复选框选择
        table.on('checkbox(hostTable)', function (obj) {
            updateHostSelection();


        });
    });


    function submitFinalData() {
        const formData = {};

        // Step 1: 主机信息
        const hostIds = $('#hostInput').data('hostIds') || [];
        if (hostIds.length > 0) {
            formData.inventory = hostIds; // ✅ 真正要提交的字段是 ID 列表
        } else {
            formData.inventory = [];
        }

        // Step 2: 表单数据
        const taskName = document.querySelector("input[name='taskName']");
        const detailLevel = document.querySelector("input[name='detail_level']");
        const forks = document.querySelector("input[name='forks']");
        const job_type = document.querySelector("select[name='taskType']");
        const playbook = document.querySelector("select[name='playbook']");
        const script = document.querySelector("select[name='script']");

        const module_name = document.querySelector("input[name='module']");
        const module_args = document.querySelector("input[name='arguments']");

        // 基础字段
        formData.name = taskName ? taskName.value : '';
        formData.verbosity = detailLevel ? detailLevel.value : '0';
        formData.forks = forks ? forks.value : '5';
        formData.job_type = job_type ? job_type.value : '';

        // 根据任务类型添加不同字段
        if (job_type && job_type.value === 'playbook') {
            formData.playbook = playbook && playbook.value ? playbook.value : '';
        } else if (job_type && job_type.value === 'script') {
            formData.script = script && script.value ? script.value : '';

        } else if (job_type && job_type.value === 'ad-hoc') {
            formData.module_name = module_name ? module_name.value : '';
            formData.module_args = module_args ? module_args.value : '';
        }

        // 发送到后端
        $.ajax({
            url: '{% url "runner_jobs:job-create" %}',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            headers: {
                'X-CSRFToken': $('meta[name="csrf-token"]').attr('content') // 如果你用了 CSRF token
            },
            success: function (response) {
                {#alert('任务创建成功！');#}


                var index = parent.layer.getFrameIndex(window.name); // 先得到当前 iframe 层的索引
                parent.layer.close(index); // 再执行关闭
            },
            error: function (xhr) {
                try {
                    const err = JSON.parse(xhr.responseText);
                    alert('创建失败：' + (err.message || '未知错误'));
                } catch (e) {
                    alert('创建失败：' + xhr.responseText);
                }
            }
        });
    }


    // jQuery 扩展：将表单转换成对象
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
</script>
</body>
</html>
